import React, { useState, useEffect } from 'react';
import type { AccountRead, CategoryRead, TransactionStore, TransactionSplitStore, TransactionRead } from '../types';
import Spinner from './ui/Spinner';
import XMarkIcon from './icons/XMarkIcon';

interface CreateTransactionModalProps {
  isOpen: boolean;
  onClose: () => void;
  accounts: AccountRead[];
  categories: CategoryRead[];
  onSave: (transaction: TransactionStore, id?: string) => Promise<void>;
  transactionToEdit: TransactionRead | null;
}

const CreateTransactionModal: React.FC<CreateTransactionModalProps> = ({ isOpen, onClose, accounts, categories, onSave, transactionToEdit }) => {
  const [transactionType, setTransactionType] = useState<'withdrawal' | 'deposit'>('withdrawal');
  const [description, setDescription] = useState('');
  const [amount, setAmount] = useState('');
  const [accountId, setAccountId] = useState('');
  const [categoryName, setCategoryName] = useState('');
  const [isAddingNewCategory, setIsAddingNewCategory] = useState(false);
  const [tags, setTags] = useState('');
  const [date, setDate] = useState(new Date().toISOString().split('T')[0]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const isEditMode = transactionToEdit !== null;

  useEffect(() => {
    if (isOpen) {
      if (isEditMode) {
        const split = transactionToEdit.attributes.transactions[0];
        if (split.type === 'withdrawal' || split.type === 'deposit') {
            setTransactionType(split.type);
            setDescription(split.description);
            setAmount(split.amount);
            setDate(new Date(split.date).toISOString().split('T')[0]);
            setAccountId(split.source_id || split.destination_id || '');
            setTags(split.tags?.join(', ') || '');
            setError(null);

            // Enhanced category logic
            const existingCategory = categories.find(c => c.attributes.name === split.category_name);
            if (split.category_name && !existingCategory) {
                // Category from transaction doesn't exist in the main list, switch to "add new" mode
                setIsAddingNewCategory(true);
                setCategoryName(split.category_name);
            } else {
                setIsAddingNewCategory(false);
                setCategoryName(split.category_name || '');
            }

        } else {
            resetForm();
            setError("编辑此交易类型不被支持。");
        }
      } else {
        resetForm();
      }
    }
  }, [isOpen, transactionToEdit, isEditMode, accounts, categories]);
  
  const resetForm = () => {
      setTransactionType('withdrawal');
      setDescription('');
      setAmount('');
      setCategoryName('');
      setIsAddingNewCategory(false);
      setTags('');
      setDate(new Date().toISOString().split('T')[0]);
      setError(null);
      setIsSubmitting(false);
      if (accounts.length > 0) {
          setAccountId(accounts[0].id);
      }
  };

  const handleClose = () => {
    onClose();
    setTimeout(resetForm, 300);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!description || !amount || !accountId) {
      setError("请填写所有必填字段。");
      return;
    }
    setError(null);
    setIsSubmitting(true);
    
    const tagsArray = tags.split(',').map(t => t.trim()).filter(Boolean);

    const transactionSplit: TransactionSplitStore = {
      type: transactionType,
      date,
      amount,
      description,
      category_name: categoryName,
      tags: tagsArray.length > 0 ? tagsArray : undefined,
    };

    if (transactionType === 'withdrawal') {
      transactionSplit.source_id = accountId;
      transactionSplit.destination_name = categoryName || '未分类';
    } else { // deposit
      transactionSplit.destination_id = accountId;
      transactionSplit.source_name = categoryName || '未分类';
    }

    const payload: TransactionStore = {
      transactions: [transactionSplit],
    };

    try {
      await onSave(payload, isEditMode ? transactionToEdit.id : undefined);
      handleClose();
    } catch (err) {
      setError('创建交易失败，请重试。');
      console.error(err);
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!isOpen) {
    return null;
  }

  const inputClasses = "w-full bg-slate-700/50 border border-slate-600 rounded-lg px-3 py-2 text-white placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-cyan-500 transition-colors";
  const labelClasses = "block text-sm font-medium text-slate-300 mb-1";

  return (
    <div className="fixed inset-0 z-50 flex items-end justify-center bg-black/60" onClick={handleClose}>
      <div 
        className={`w-full max-w-md bg-slate-800 rounded-t-3xl shadow-2xl p-6 transform transition-transform duration-300 ease-out ${isOpen ? 'translate-y-0' : 'translate-y-full'}`}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex justify-between items-center mb-4">
          <h2 className="text-xl font-bold text-white">{isEditMode ? '编辑交易' : '添加交易'}</h2>
          <button onClick={handleClose} className="text-slate-400 hover:text-white">
            <XMarkIcon className="h-6 w-6" />
          </button>
        </div>
        
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="flex bg-slate-700 rounded-full p-1">
            <button type="button" onClick={() => setTransactionType('withdrawal')} className={`w-1/2 rounded-full py-2 text-sm font-semibold transition-colors ${transactionType === 'withdrawal' ? 'bg-red-500 text-white' : 'text-slate-300'}`}>支出</button>
            <button type="button" onClick={() => setTransactionType('deposit')} className={`w-1/2 rounded-full py-2 text-sm font-semibold transition-colors ${transactionType === 'deposit' ? 'bg-green-500 text-white' : 'text-slate-300'}`}>收入</button>
          </div>

          <div>
            <label htmlFor="description" className={labelClasses}>描述</label>
            <input type="text" id="description" value={description} onChange={(e) => setDescription(e.target.value)} className={inputClasses} placeholder="例如：和朋友喝咖啡" />
          </div>

          <div className="flex space-x-4">
            <div className="w-1/2">
              <label htmlFor="amount" className={labelClasses}>金额</label>
              <input type="number" id="amount" value={amount} onChange={(e) => setAmount(e.target.value)} className={inputClasses} placeholder="0.00" step="0.01" />
            </div>
            <div className="w-1/2">
              <label htmlFor="date" className={labelClasses}>日期</label>
              <input type="date" id="date" value={date} onChange={(e) => setDate(e.target.value)} className={inputClasses} />
            </div>
          </div>

          <div>
            <label htmlFor="account" className={labelClasses}>{transactionType === 'withdrawal' ? '从账户' : '至账户'}</label>
            <select id="account" value={accountId} onChange={(e) => setAccountId(e.target.value)} className={inputClasses}>
              {accounts.map(acc => <option key={acc.id} value={acc.id}>{acc.attributes.name}</option>)}
            </select>
          </div>
          
          <div>
            <label htmlFor="category" className={labelClasses}>{transactionType === 'withdrawal' ? '支出分类' : '收入来源'}</label>
            <select
              id="category"
              value={isAddingNewCategory ? '__add_new__' : categoryName}
              onChange={(e) => {
                if (e.target.value === '__add_new__') {
                  setIsAddingNewCategory(true);
                  setCategoryName('');
                } else {
                  setIsAddingNewCategory(false);
                  setCategoryName(e.target.value);
                }
              }}
              className={inputClasses}
            >
              <option value="">-- 选择分类 --</option>
              {categories.map(cat => <option key={cat.id} value={cat.attributes.name}>{cat.attributes.name}</option>)}
              <option value="__add_new__">... 添加新分类</option>
            </select>
          </div>
          
          {isAddingNewCategory && (
            <div className="pl-2 animate-fade-in">
              <label htmlFor="new-category" className={labelClasses}>新分类名称</label>
              <input
                type="text"
                id="new-category"
                value={categoryName}
                onChange={(e) => setCategoryName(e.target.value)}
                className={inputClasses}
                placeholder="输入新的分类名称"
                autoFocus
              />
            </div>
          )}

          <div>
            <label htmlFor="tags" className={labelClasses}>标签 (用逗号分隔)</label>
            <input 
                type="text" 
                id="tags" 
                value={tags} 
                onChange={(e) => setTags(e.target.value)} 
                className={inputClasses} 
                placeholder="例如: 家庭, 购物" 
            />
          </div>

          {error && <p className="text-sm text-red-400">{error}</p>}
          
          <button type="submit" disabled={isSubmitting} className="w-full bg-cyan-600 hover:bg-cyan-500 disabled:bg-slate-600 disabled:cursor-not-allowed text-white font-bold py-3 rounded-lg transition-colors flex justify-center items-center">
            {isSubmitting ? <Spinner /> : (isEditMode ? '保存更改' : '添加交易')}
          </button>
        </form>
        <style>{`
          @keyframes fade-in {
            from { opacity: 0; transform: translateY(-5px); }
            to { opacity: 1; transform: translateY(0); }
          }
          .animate-fade-in {
            animation: fade-in 0.3s ease-out forwards;
          }
        `}</style>
      </div>
    </div>
  );
};

export default CreateTransactionModal;